package cn.edu.gcu.lost.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.gcu.lost.entity.Message;
import cn.edu.gcu.lost.entity.User;
import cn.edu.gcu.lost.service.MessageService;
import cn.edu.gcu.lost.util.U2id;

/**
 * @Describe:消息的前端控制器
 * @Date:2018-1-25 08:53:24
 */
@Controller
@RequestMapping(value = "/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    /**
     * @Description :获取信息列表（每条记录只返回部分关键字段）
     * @Param :type 信息类别，0（全部）1（失物）2（招领）
     * @Param :thing 物品类别，0（全部）1（证件）2（书本）3（财物）4（数码）5（其他）
     * @Param :self 标志是否只返回我发布的  0（全部）1（我发布的）
     * @Param :status 处理状态，0（全部）1（已处理）2（未处理）
     * @Param :search 搜索栏
     * @Param :start 分页开始位置（默认0）
     * @Param :size 分页大小（默认10）
     * @Date :2018-1-25 09:05:38
     * @Author:Rocky
     */
    @ResponseBody
    @RequestMapping(value = "/findList")
    public Object findList(@RequestParam(required = true) String type, @RequestParam(required = true) String thing,
                           @RequestParam(required = true) String self, @RequestParam(required = true) String status,
                           @RequestParam(required = false) String search, @RequestParam(required = false, defaultValue
            = "0") String start, @RequestParam(required = false, defaultValue = "10") String size, HttpServletRequest
                                   request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String selfId = null;
        //登陆验证
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "no login error");
            return resultMap;
        }
        selfId = user.getOpenid();
        //参数验证
        type = type.trim();
        thing = thing.trim();
        self = self.trim();
        status = status.trim();
        if (!type.equals("0") && !type.equals("1") && !type.equals("2")) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "Param value error(type)");
            return resultMap;
        }
        if (!thing.equals("0") && !thing.equals("1") && !thing.equals("2") && !thing.equals("3")
                && !thing.equals("4") && !thing.equals("5")) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "Param value error(thing)");
            return resultMap;
        }
        if (!self.equals("0") && !self.equals("1")) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "Param value error(self)");
            return resultMap;
        }
        if (!status.equals("0") && !status.equals("1") && !status.equals("2")) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "Param value error(status)");
            return resultMap;
        }
        List<Message> messageList = messageService.findList(type, thing, self, selfId, status, search, Integer
                .parseInt(start), Integer.parseInt(size));
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Integer totalNum = messageService.countNum(type, thing, self, selfId, status, search);
        dataMap.put("messageList", messageList);
        dataMap.put("totalNum", totalNum);
        resultMap.put("data", dataMap);
        resultMap.put("result", "success");
        return resultMap;
    }

    @ResponseBody
    @RequestMapping(value = "/countNum")
    public Object countNum(@RequestParam(required = true) String type, @RequestParam(required = true) String thing,
                           @RequestParam(required = true) String self, @RequestParam(required = true) String status,
                           @RequestParam(required = false) String search, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String selfId = null;
        //登陆验证
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "no login error");
            return resultMap;
        }
        selfId = user.getOpenid();
        //参数验证
        type = type.trim();
        thing = thing.trim();
        self = self.trim();
        status = status.trim();
        if (!type.equals("0") && !type.equals("1") && !type.equals("2")) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "Param value error(type)");
            return resultMap;
        }
        if (!thing.equals("0") && !thing.equals("1") && !thing.equals("2") && !thing.equals("3")
                && !thing.equals("4") && !thing.equals("5")) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "Param value error(thing)");
            return resultMap;
        }
        if (!self.equals("0") && !self.equals("1")) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "Param value error(self)");
            return resultMap;
        }
        if (!status.equals("0") && !status.equals("1") && !status.equals("2")) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "Param value error(status)");
            return resultMap;
        }
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Integer totalNum = messageService.countNum(type, thing, self, selfId, status, search);
        dataMap.put("totalNum", totalNum);
        System.out.println(totalNum);
        resultMap.put("data", dataMap);
        resultMap.put("result", "success");
        return resultMap;
    }


    /**
     * @Description:获取一条信息的详情
     * @Param :id 消息的唯一标识id
     * @Data:2018-01-25 10:23:25
     * @Author:Rocky
     */
    @ResponseBody
    @RequestMapping(value = "findDetail")
    public Object findDetail(@RequestParam(required = true) String id, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //登陆验证
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "no login error");
            return resultMap;
        }
        Message message = messageService.findDetail(id);
        if (message == null) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "no exist error");
            return resultMap;
        }
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("message", message);
        resultMap.put("data", dataMap);
        resultMap.put("result", "success");
        return resultMap;
    }

    /**
     * @Description:发布一条信息
     * @Param :message消息实体，封装所以字段
     * @Date:2018-01-25 10:27:33
     * @Author:Rocky
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public Object save(@Valid @ModelAttribute("message") Message message, Errors errors, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (errors.hasErrors()) {
            for (Object object : errors.getAllErrors()) {
                System.out.println(object);
            }
            resultMap.put("result", "faild");
            resultMap.put("cause", "param valid error");
            return resultMap;
        }
        //登陆验证
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            resultMap.put("result", "faild");
            resultMap.put("cause", "no login error");
            return resultMap;
        }
        message.setCreateby(user.getOpenid());
        message.setId(U2id.getUUID());
        message.setCreatedate(new Date());
        message.setStatus("2");
        message.setRealName(user.getUsername());
        //此处限于云之家没有学号字段
        message.setStudentId(user.getMobile());
        if (message.getLinkman().trim().equals("12345678")) {
            message.setLinkman(user.getUsername());
        } else {
            message.setLinkman(message.getLinkman().trim());
        }
        if (messageService.save(message)) {
            resultMap.put("result", "success");
            resultMap.put("data", null);
        } else {
            resultMap.put("result", "faild");
            resultMap.put("data", null);
        }
        return resultMap;
    }

	
	/*
	 * 
	 
	  接口：doFinish（）将message处理状态改为已处理
	   	  1.参数：(String) id ----message记录id
		  2.返回结果：	result:success||result:error;  获取用户信息成功/失败
						operate:faild ||operate:success 修改成功/失败 
	 * 
	 * 
	 */


    @ResponseBody
    @RequestMapping("/doFinish")
    public Map<String, Object> doFinish(@RequestParam(value = "id", required = true) @Valid String id,
                                        HttpServletRequest
                                                request) {
        Map<String, Object> resultMap = new HashMap<String, Object>(16);
        resultMap.put("operate", "faild");
        if (request.getSession().getAttribute("user") == null) {
            resultMap.put("result", "faild");
            return resultMap;
        }
        resultMap.put("result", "success");
        if (messageService.updateStatusByid(id)) {
            resultMap.put("operate", "success");

        }
        return resultMap;

    }
	
	
	
	/*
	 * 
	 
	  接口：delete（）删除message单条记录
	   	  1.参数：(String)  id ----message记录id
		  2.返回结果：	result:success||result:error;  获取用户信息成功/失败
						operate:faild ||operate:success 修改成功/失败 
	 * 
	 * 
	 */


    @ResponseBody
    @RequestMapping("/delete")
    public Map<String, Object> delete(@RequestParam(value = "id", required = true) String id, HttpServletRequest
            request) {

        Map<String, Object> resultMap = new HashMap<String, Object>(16);
        resultMap.put("operate", "faild");
        if (request.getSession().getAttribute("user") == null) {
            resultMap.put("result", "faild");
            return resultMap;
        }
        if (messageService.deleteById(id)) {
            resultMap.put("operate", "success");

        }
        resultMap.put("result", "success");
        return resultMap;

    }

	/*
	 * 
	 
	  接口：deleteMore（）删除多条message记录
	   	  1.参数：(String)  ids ----多个message记录id拼接,以英文分号划分   
	   	  	example:ids=18eee99c5ab944a9a97a684213;18eee99c5ab944a9a97a6842134
		  
		  2.返回结果：
		        	 1.成功：	  {"result":"success","cause":"success"}
	 * 				 2.输入格式错误或不存在-部分删除失败{"result":"faild","cause":"partial operation faild"}
	 * 				 3.输入格式错误或不存在-全部删除失败{"result":"faild","cause":   "all  operation faild"}
	 */


    @ResponseBody
    @RequestMapping("/deleteMore")
    public Map<String, Object> deleteMore(@RequestParam(value = "ids", required = true) String ids,
                                          HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>(16);
        resultMap.put("result", "faild");
        if (request.getSession().getAttribute("user") == null) {
            resultMap.put("cause", "not exit");
            return resultMap;
        }
        String cause = messageService.deleteMore(ids);
        if ("sucess".equals(cause)) {
            resultMap.put("result", "success");
            resultMap.put("cause", "success");
            return resultMap;
        }
        resultMap.put("cause", cause);
        return resultMap;
    }


}
